package com.lagou.filter;

import com.lagou.bean.BeanMonitor;
import com.lagou.bean.MonitorManager;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Activate(group = CommonConstants.CONSUMER)
public class TPMonitorFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = 0;
        try {
            startTime = System.currentTimeMillis();
            //执行方法
            return invoker.invoke(invocation);
        } finally {
            long invokeTime = System.currentTimeMillis() - startTime;
            //System.out.println("invoke time:"+ invokeTime + "ms");
            BeanMonitor beanMonitor = BeanMonitor.builder()
                    .serviceName(invocation.getServiceName())
                    .methodName(invocation.getMethodName())
                    .invokeTime(invokeTime)
                    .statisticsDate(new Date())
                    .build();
            MonitorManager.getInstance().addBeanMonitor(beanMonitor);
        }
    }
}
